import *as types from '../actions/types'

const default_state = {
    notifications: [],
    current_page: 1,
    end_of_page: false,
    loading: true,
    error: false,
    per: 10
}

const notification = (state = default_state, action) => {
    switch (action.type) {
        case types.FETCHING_NOTIFICATION:
            return {
                ...state,
                loading: true
            }
        case types.FETCH_NOTIFICATION_SUCCESS:
            state.notifications.push(...action.notifications)
            return {
                ...state,
                notifications: state.notifications,
                loading: false,
                error: false,
                current_page: state.current_page + 1
            }
        case types.NOTIFICATION_END_OF_PAGE:
            return {
                ...state,
                end_of_page: true
            }
        case types.FETCH_NOTIFICATION_FAIL:
            return {
                ...state,
                error: true
            }
        case types.REFRESH_NOTIFICATIONS:
            return {
                notifications: [],
                current_page: 1,
                end_of_page: false,
                loading: true,
                error: false,
                per: 10
            }
        case types.UPDATE_NOTIFICATION:
            let notification = (state.notifications.filter((notification) => {
                return notification.id == action.id
            }))[0]
            if (notification != undefined) {
                Object.keys(action.param).forEach((key) => {
                    notification[key] = action.param[key]
                })
            }
            return {
                ...state,
                notifications: state.notifications
            }
        default:
            return state
    }
}

export default notification
